package edu.gyc.hisecurity.validate;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//OncePerRequestFilter 只会被调用一次的过滤器
@Slf4j
public class ValidateCodeFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("Request url {}",request.getRequestURI());
        String targetPath = request.getContextPath() + "/doLogin";
        if (StringUtils.equals(targetPath, request.getRequestURI()) &&
                StringUtils.equalsIgnoreCase(request.getMethod(), "post")) {
            try{
                validate(new ServletWebRequest(request));
            }catch (ValidateCodeException e){
                    log.info(e.toString());

                request.setAttribute("msg",e.toString());
             request.getRequestDispatcher("/").forward(request,response);
                return;
            }

        }

        filterChain.doFilter(request,response);
    }

    private void validate(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {
        HttpSession session=servletWebRequest.getRequest().getSession();
        ImageCode imageCodeInSession = (ImageCode)session.getAttribute("VALIDATE_CODE");
      //  log.info("session validate code {}",imageCodeInSession.getCode());


        String  codeInRequest= ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(),"verifyCode");

        if (StringUtils.isBlank(codeInRequest)) {
            throw new ValidateCodeException("验证码的值不能为空");
        }

        if (imageCodeInSession == null) {
            throw new ValidateCodeException("验证码不存在");
        }

        if(imageCodeInSession.isExpired()){
            servletWebRequest.getRequest().getSession().removeAttribute("VALIDATE_CODE");
           throw new ValidateCodeException("验证码过期");
        }

        if (!StringUtils.equalsIgnoreCase(imageCodeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException("验证码不匹配");
        }

        servletWebRequest.getRequest().getSession().removeAttribute("VALIDATE_CODE");
    }
}
